/*
 * @Author: your name
 * @Date: 2021-09-19 10:33:55
 * @LastEditTime: 2021-09-20 12:12:42
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \more-money\src\models\TagsListModel.ts
 */
const localStorageKeyName = 'TagList';

const TagsListModel = {
    getList(){
        const res = JSON.parse(window.localStorage.getItem(localStorageKeyName) || '[]');
        // || '[]'是为了当getItem为空时赋予默认值从而解决ts纠错
        return res;
    },
    create(params: Tag){
        const res = this.getList();
        let isRepeat = false;
        res.forEach((item: Tag)=>{
            if(item.name === params.name){
                isRepeat = true;
            }
        })
        if(isRepeat){
            return 'Duplicated';
        }else{
            res.push(params);
            this.updateList(res);
            return 'Success';
        }
    },
    delete(params: Tag): string{
        const res = this.getList();
        let isExist = false;
        res.forEach((item: Tag,index: number)=>{
            if(item.name === params.name){
                isExist = true;
                this.updateList([...res.slice(0,index),...res.slice(index+1)]);
            }
        })
        if(isExist){
            return 'NotFound';
        }else{
            return 'Success'
        }
    },
    updateList(list: Tag[]){
        window.localStorage.setItem(localStorageKeyName, JSON.stringify(list));
    }
}

export default TagsListModel;
